import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {AccountService} from "../../service/account.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {Router} from '@angular/router';

@Component({
  selector: 'app-login-box',
  templateUrl: './login-box.component.html',
  styleUrls: ['./login-box.component.less']
})
export class LoginBoxComponent implements OnInit {

  @Input('type') type: string = ''

  validateForm!: FormGroup;
  remember = true;

  submitLoading = false

  showOtherToken = false

  constructor(
    private fb: FormBuilder,
    private accountService: AccountService,
    private message: NzMessageService,
    public router: Router
  ) {
  }

  submitForm(): void {
    if (this.validateForm.valid) {
      this.doAction()
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      })
    }
  }

  doAction() {
    this.submitLoading = true
    const form = this.validateForm.value
    if (this.type === 'login') {
      this.accountService.login(form, (success) => {
        if (success) {
          this.message.success('登录成功')
          this.goHome()
        }
        this.submitLoading = false
      })
    } else {
      this.accountService.register(form, (success => {
        if (success) {
          this.message.success('注册成功')
          this.goHome()
        }
        this.submitLoading = false
      }))
    }
  }

  private goHome() {
    this.router.navigateByUrl('/home').then(r => {})
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      token: [null],
      remember: [false]
    })
  }

  buttonTitle(): string {
    if (this.type === 'login') {
      return '登录'
    } else {
      return "注册"
    }
  }

  tokenInputChange() {
    this.showOtherToken = !this.showOtherToken
  }

  elseRouteLink(): string {
    if (this.type === 'login') {
      return '/register'
    } else {
      return '/login'
    }
  }

  elseTitle(): string {
    if (this.type !== 'login') {
      return '登录'
    } else {
      return "注册"
    }
  }

}
